import React from 'react';
import PropTypes from 'prop-types';


// 文字过长时默认收起
// 默认展示长度是 20 个字
class TextOverflow extends React.Component {

  constructor(p) {
    super(p);
    this.trigger = this.trigger.bind(this);
    const text = this.props.text;
    const length = this.props.length;
    const isLong = text.length > length;

    this.state = {
      originText: text,
      length,
      text: isLong ? `${text.substr(0, length)}...` : text,
      showAll: false,
      isLong,
    };
  }

  trigger() {
    this.setState({
      showAll: !this.state.showAll,
    });
  }

  render() {
    const {
      text,
      originText,
      isLong,
      showAll,
    } = this.state;

    return (
      <div style={{ maxWidth: 200 }}>
        {
          showAll ? originText : text
        }
        {
          isLong && (
            <a onClick={this.trigger}>
              {showAll ? '收起' : '展开' }
            </a>
          )
        }
      </div>
    );
  }
}

TextOverflow.propTypes = {
  length: PropTypes.number,
  text: PropTypes.string,
};

TextOverflow.defaultProps = {
  length: 30,
};

export default TextOverflow;
